import { ref } from 'vue'

export const useScroll = (ele: HTMLElement, page: any, list: any, pageSize: any) => {
	let timer = 0
	if(ele == null || ele == undefined) return;
	let scrollbarView = ele.querySelector('.el-scrollbar__view') as HTMLElement
	let scrollbarWrap = ele.querySelector('.el-scrollbar__wrap') as HTMLElement
	let scrollTop = ref(scrollbarWrap.scrollTop)
	let maxScrollTop = scrollbarView?.clientHeight - scrollbarWrap?.clientHeight
	let animationId = 0
	function smoothScroll() {
		scrollTop.value += 0.1 // 增加滚动高度
		// 如果达到最大滚动高度，重置滚动位置
		if (scrollTop.value >= maxScrollTop) {
			scrollTop.value = 0
			scrollbarWrap?.scrollTo({ top: scrollTop.value })
			page = page >= Math.ceil(list.value.length / pageSize) ? 1 : page + 1
			// page.value = page.value >= Math.ceil(list.value.length / pageSize.value) ? 1 : page.value + 1
		}

		// 平滑滚动到新的位置
		scrollbarWrap?.scrollTo({ top: scrollTop.value, behavior: 'smooth' })

		// 继续下一帧
		animationId = requestAnimationFrame(smoothScroll)
	}
	function setScroll() {
		scrollbarWrap?.scrollTo({ top: scrollTop.value })
	}
	// 启动动画
	smoothScroll()
	ele.addEventListener('mouseenter', () => cancelAnimationFrame(animationId))
	ele.addEventListener('mouseleave', () => {
		if (scrollTop.value) {
			scrollTop.value = scrollbarWrap.scrollTop
		}
		smoothScroll()
	})

	return { scrollTop, setScroll }
}
